﻿using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MCGLib.Common;
using Microsoft.Win32;

namespace CreateCode
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        
        private void btnCreateCode_Click(object sender, RoutedEventArgs e)
        {
            string SavePath = txtSavePath.Text.Replace("保存路径：", "");
            //if (string.IsNullOrEmpty(SavePath)) { MessageBox.Show("请选择保存路径"); return; }
            if (string.IsNullOrEmpty(txtClassName.Text)) { MessageBox.Show("类库名称不能为空"); return; }
            if (string.IsNullOrEmpty(txtString.Text)) { MessageBox.Show("JSON字符串不能为空"); return; }
            var model = ConvertJSON.CreateModel(txtString.Text.Trim(), txtModelName.Text.Trim());
            string PathLib = AppDomain.CurrentDomain.BaseDirectory;
            string Pathmodel = System.IO.Path.Combine(string.IsNullOrEmpty(SavePath)?PathLib:SavePath,  txtClassName.Text.Trim());
            if (Directory.Exists(Pathmodel)) Directory.Delete(Pathmodel, true);
            if (ExecuteDotnetCommand("dotnet", $"new classlib -n {txtClassName.Text.Trim()} --output {Pathmodel}"))
            {
                if(File.Exists(System.IO.Path.Combine(Pathmodel, "Class1.cs")))
                File.Delete(System.IO.Path.Combine(Pathmodel, "Class1.cs"));
                CreateClassFile(model, Pathmodel);
                File.Copy(System.IO.Path.Combine(PathLib, "MCGLib.dll"), System.IO.Path.Combine(Pathmodel, "MCGLib.dll"));
                string Addrefer = @" <ItemGroup>
   <Reference Include=""MCGLib"">
     <HintPath>MCGLib.dll</HintPath>
   </Reference>
 </ItemGroup>
	
</Project>";
                using (var reader = new StreamReader(System.IO.Path.Combine(Pathmodel, "Models.csproj")))
                {
                    Addrefer = reader.ReadToEnd().Replace("</Project>", Addrefer);
                }

                using (var fs = new StreamWriter(System.IO.Path.Combine(Pathmodel, $"{txtClassName.Text.Trim()}.csproj")))
                {
                    fs.WriteLine(Addrefer);
                }
                //ExecuteDotnetCommand("dotnet", $"add reference {System.IO.Path.Combine(Pathmodel, "MCGLib.dll")}") &&
                if (ExecuteDotnetCommand("dotnet", $"build {Pathmodel}"))
                    MessageBox.Show("编译成功");
                else
                    MessageBox.Show("生成成功，但编译失败");
            }
            else MessageBox.Show("生成失败");
        }
        bool ExecuteDotnetCommand(string command, string arguments)
        {
            ProcessStartInfo psi = new ProcessStartInfo()
            {
                Arguments = arguments,
                FileName = command,
                UseShellExecute = false,//不使用操作系统的外壳程序来启动进程
                CreateNoWindow = true,
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                StandardErrorEncoding = Encoding.UTF8,
                StandardOutputEncoding = Encoding.UTF8,
            };           
            return Process.Start(psi)!.StandardOutput.ReadToEnd().Contains("已成功");

        }
        private async void CreateClassFile(MCGLib.Models.CreateClass model, string path)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("using System;\r\nusing System.Collections.Generic;\r\nusing System.Globalization;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n");
            sb.Append("using MCGLib.Common;\r\n\r\n\r\n");
            sb.Append("namespace Models\r\n");
            sb.Append('{');
            if (!string.IsNullOrEmpty(model.JsonName))
                sb.Append($"\r\n   [McgJsonName(\"{model.JsonName}\")]\r\n");
            sb.Append($"\r\n   public class {model.ClassName}\r\n   {{");
            foreach (var item in model.Properties)
            {
                if (item.CreateModelChild != null)
                    CreateClassFile(item.CreateModelChild, path);
                if (!string.IsNullOrEmpty(item.JsonName))
                    sb.Append($"\r\n        [McgJsonProperty(\"{item.JsonName}\")]\r\n");
                sb.Append($"        public {item.DataType} {item.PropertyName} {{ get; set; }}\r\n");
            }
            sb.Append("    ");
            sb.Append('}');
            sb.Append("\r\n");
            sb.Append('}');
            using (var fs = new FileStream(System.IO.Path.Combine(path, $"{model.ClassName}.cs"), FileMode.OpenOrCreate))
            {
                await fs.WriteAsync(Encoding.UTF8.GetBytes(sb.ToString()));
            }
            txtResult.Text += sb.ToString();
        }

        private void btnPath_Click(object sender, RoutedEventArgs e)
        {
            var opendia = new OpenFolderDialog();
            bool? isOpen = opendia.ShowDialog();
            if (isOpen!=null&&isOpen==true)
            {
                txtSavePath.Text="保存路径："+ opendia.FolderName;
            }
           
        }
    }
}